let app = document.getElementById('app')

let dpr = window.devicePixelRatio

let canvas = document.createElement('canvas')
canvas.width = window.innerWidth * dpr
canvas.height = window.innerHeight * dpr
app.appendChild(canvas)

let gl = canvas.getContext('webgl', {
    antialias: true
})

let viewportSize = Math.min(canvas.width, canvas.height);
let x = (canvas.width - viewportSize) / 2;
let y = (canvas.height - viewportSize) / 2;
gl.viewport(x, y, viewportSize, viewportSize)
gl.clearColor(0.0, 0.1, 0.1, 1.0)
gl.clear(gl.COLOR_BUFFER_BIT)

// 顶点着色器
let vertexShader = gl.createShader(gl.VERTEX_SHADER)
gl.shaderSource(vertexShader, `
  attribute vec2 a_Position;
  void main() {
    gl_Position = vec4(a_Position, 0.0, 1.0);
    gl_PointSize = 10.0;
  }
`)
gl.compileShader(vertexShader)

// 片元着色器
let fragmentShader = gl.createShader(gl.FRAGMENT_SHADER)
gl.shaderSource(fragmentShader, `
  void main() {
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
  }
`)
gl.compileShader(fragmentShader)

// 创建着色器程序
let program = gl.createProgram()
gl.attachShader(program, vertexShader)
gl.attachShader(program, fragmentShader)
gl.linkProgram(program)
gl.useProgram(program)

// 获取顶点着色器中的变量
let a_Position = gl.getAttribLocation(program, 'a_Position')

// 创建圆形的顶点数据
let circleVertices = [0, 0]  // 添加圆心坐标作为第一个顶点
let r = 0.2  // 半径
let segments = 50  // 分段数

// 计算圆形的顶点坐标
for (let i = 0; i <= segments; i++) {
    let angle = i * Math.PI * 2 / segments
    let x = r * Math.cos(angle)
    let y = r * Math.sin(angle)
    circleVertices.push(x, y)
}

console.log(circleVertices)

// 创建缓冲区对象
let circleBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, circleBuffer)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(circleVertices), gl.STATIC_DRAW)

// 将缓冲区对象分配给a_Position变量
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0)
gl.enableVertexAttribArray(a_Position)

// 使用 TRIANGLE_FAN 绘制填充圆形
gl.drawArrays(gl.TRIANGLE_FAN, 0, segments + 2)  // 顶点数量加2（包含圆心和闭合点）

// 创建一个点的坐标
let vertices = new Float32Array([1.0, 0.0])

// 创建缓冲区对象
let vertexBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer)
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW)

// 将缓冲区对象分配给a_Position变量
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0)
gl.enableVertexAttribArray(a_Position)

// 绘制一个点
gl.drawArrays(gl.POINTS, 0, 1)

// 创建两个点的坐标
let lineVertices = new Float32Array([
    -0.5, 0.5,  // 第一个点
    0.5, -0.5    // 第二个点
])

// 创建新的缓冲区对象
let lineBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, lineBuffer)
gl.bufferData(gl.ARRAY_BUFFER, lineVertices, gl.STATIC_DRAW)

// 将缓冲区对象分配给a_Position变量
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0)
gl.enableVertexAttribArray(a_Position)

// 绘制一条线
gl.drawArrays(gl.LINES, 0, 2)
